import fileServices from '@/services/file';
import {message, Modal, Upload} from 'antd';
import type {UploadFile, UploadProps} from 'antd/es/upload/interface';
import {PlusOutlined} from '@ant-design/icons';
import {getFullImageUrl, verfiyImage} from '@/utils/fileUtil';
import React, {useCallback, useEffect, useState} from 'react';

const {upload, removeUrlSuffix} = fileServices.FileController;


interface ImageListProps {
    images: string[];
    onChange?: (images: string[], saveImage: string[]) => void;
}

/**
 * 编辑用的图片展示
 * @param images 图片地址
 * @returns
 */
const EditImageList: React.FC<ImageListProps> = ({images, onChange}) => {
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState<UploadFile[]>([]);

    useEffect(() => {
        setFileList(images.map((img, index) => ({
            uid: `-${index}`,
            name: img,
            status: 'done',
            url: getFullImageUrl(img),
        })));
    }, [images]);


    /**
     * 改变触发器
     */
    const updateFileList = useCallback((newFileList: UploadFile[]) => {
            setFileList(newFileList);
            const newImages = newFileList.map(file => file.url || '');
            const saveImages = newFileList.map(file => {
                // 新上传的图片
                if (file.response && file.response.name) {
                    return file.response.name;
                }
                // 已有的图片或其他情况
                else {
                    // 移除 URL 的前缀，只保留相对路径
                    const fullPath = file.name || file.url || '';
                    const match = fullPath.match(/\/images\/.*$/);
                    return match ? match[0] : fullPath;
                }
            });
            onChange?.(newImages.filter(url => url), saveImages);
        }, [onChange]);

    /**
     * 预览
     */
    const handlePreview = (file: UploadFile) => {
        setPreviewImage(file.url || file.preview!);
        setPreviewVisible(true);
    };

    /**
     * 上传
     */
    const handleUpload: UploadProps['customRequest'] = async (options) => {
        const {file, onSuccess, onError} = options;
        if (!file) return true;
        try {
            // await upload(API.defUploadFile(file as File));
            const response = await upload({
                bucket: 'production',
                childFolder: 'production/',
                file: file as File,
            });
            if (response.success && response.data && response.data.urlSuffix) {
                const urlSuffix = response.data.urlSuffix;
                const newFile: UploadFile<any> = {
                    name: urlSuffix,
                    status: "done",
                    uid: response.data.id?.toString() || '', // Ensure uid is a string or empty string
                    url: getFullImageUrl(urlSuffix),
                    response: {
                        name: urlSuffix
                    }
                };
                onSuccess?.(newFile, file as any); // No need to cast file as any here

                // Assuming fileList and updateFileList are defined and accessible
                // You might need to adjust this part based on your actual state management
                const newFileList = [...fileList, newFile];
                updateFileList(newFileList);
                message.success('上传成功');
            } else {
                onError?.(new Error('上传失败'));
                message.error('上传失败');
            }
        } catch (error) {
            onError?.(error as any);
            // message.error('上传失败');
        }
    };

    /**
     * 删除
     */
    const handleRemove = async (file: UploadFile) => {
        try {
            await removeUrlSuffix(file.name);
            const newFileList = fileList.filter(item => item.uid !== file.uid);
            updateFileList(newFileList);
            return true;
        } catch (error) {
            return false;
        }
    };


    const uploadButton = (
        <div>
            <PlusOutlined/>
            <div style={{marginTop: 8}}>Upload</div>
        </div>
    );

    return (

        <>
            <Upload
                listType="picture-card"
                fileList={fileList}
                onPreview={handlePreview}
                onRemove={handleRemove}
                customRequest={handleUpload}
                beforeUpload={verfiyImage}
                accept="image/*"
            >
                {fileList.length >= 8 ? null : (
                    <div>
                        <PlusOutlined/>
                        <div style={{marginTop: 8}}>Upload</div>
                    </div>
                )}
            </Upload>
            <Modal
                open={previewVisible}
                footer={null}
                onCancel={() => setPreviewVisible(false)}
            >
                <img alt="preview" style={{width: '100%'}} src={previewImage}/>
            </Modal>
        </>
    );
};

export default EditImageList;
